package cn.bearspark.common.parse.html;

import cn.bearspark.common.parse.Parser;

/**
 * br 标签的解析器
 *
 * @author f
 */
public class TagBrParser extends Parser<HtmlTextParseContext> {
    @Override
    public void parse() {
        HtmlTextParseContext context = pipeline().getContext();
        String src = context.getBody();
        int index = 0;
        while (true) {
            int openIndex = src.indexOf("<br>", index);
            if (openIndex == -1) {
                context.setBody(src);
                return;
            }
            src = src.substring(0, openIndex) +
                  "<b>" +
                  src.substring(openIndex + "<br>".length());
            index = openIndex + "<br>".length();
        }
    }

    @Override
    public void unparse() {
        HtmlTextParseContext context = pipeline().getContext();
        String tar = context.getBody();
        int index = 0;
        while (true) {
            int openIndex = tar.indexOf("<b>", index);
            if (openIndex == -1) {
                context.setBody(tar);
                return;
            }
            tar = tar.substring(0, openIndex) +
                  "<br>" +
                  tar.substring(openIndex + "<b>".length());
            index = tar.indexOf("<br>", openIndex) + "<br>".length();
        }
    }
}
